package com.atguigu.gulimall.cart.interceptor;

import com.atguigu.common.vo.MemberRspVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@Component
public class CartInterceptor implements HandlerInterceptor {
    public static ThreadLocal<UserInfoTo> threadLocal=new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberRspVo memberRspVo= (MemberRspVo) session.getAttribute("loginUser");
        if (memberRspVo!=null){
            userInfoTo.setUserId(memberRspVo.getId());
        }

        Cookie[] cookies = request.getCookies();
        //请求中是否用userkey
        if (cookies!=null && cookies.length>0){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("userKey")){
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setUserTemp(true);
                }
            }
        }
        //请求中没有userkey
        if (StringUtils.isEmpty(userInfoTo.getUserKey())){
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }
        threadLocal.set(userInfoTo);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        //第一次登录，设置cookie 设置过期时间
        if (!userInfoTo.getUserTemp()){
            Cookie cookie = new Cookie("userKey", userInfoTo.getUserKey());
            cookie.setMaxAge(60*60*24*30);
            cookie.setDomain("gulimall.com");
            response.addCookie(cookie);
        }
    }
}
